package com.sondertara.joya.core.jdbc.support.dialect;

import com.sondertara.joya.core.jdbc.support.DbType;
import com.sondertara.joya.core.jdbc.support.dialect.PageSqlDialect;
import com.sondertara.joya.core.jdbc.support.dialect.SqlDialectRegister;
import com.sondertara.joya.exceptions.DbException;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

public class DialectFactory {

    public static DbType getDatabaseType(Connection connection) {
        try {

            String databaseType = connection.getMetaData().getDatabaseProductName();
            String databaseName = commonDatabaseName(databaseType);

            DbType dbType = DbType.of(databaseName);
            if (dbType == null) {
                throw new IllegalArgumentException("Not support for database:" + databaseType);
            }
            return dbType;
        } catch (SQLException e) {
            throw new DbException(e);
        }
    }
    public static DbType getDatabaseType(DatabaseMetaData databaseMetaData) {
        try {

            String databaseType = databaseMetaData.getDatabaseProductName();
            String databaseName = commonDatabaseName(databaseType);

            DbType dbType = DbType.of(databaseName);
            if (dbType == null) {
                throw new IllegalArgumentException("Not support for database:" + databaseType);
            }
            return dbType;
        } catch (SQLException e) {
            throw new DbException(e);
        }
    }

    public static String commonDatabaseName(String source) {
        String name = source;
        if (source != null && source.startsWith("DB2")) {
            name = "DB2";
        } else if ("Sybase SQL Server".equals(source) ||
                "Adaptive Server Enterprise".equals(source) ||
                "ASE".equals(source) ||
                "sql server".equalsIgnoreCase(source)) {
            name = "Sybase";
        }
        return name;
    }

    public static PageSqlDialect getDialect(Connection connection) {
        DbType databaseType = getDatabaseType(connection);
        return (PageSqlDialect) SqlDialectRegister.findOrCreate(databaseType);
    }
}
